/**
 * 
 */
package com.yinhai.activity;

import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.yinhai.adapter.ContactAdpter;
import com.yinhai.asynctask.BaseTask;
import com.yinhai.constant.Contact;
import com.yinhai.model.UserUserContact;
import com.yinhai.service.ContactUserServiceImpl;

/**
 * @author 通讯录界面
 * 
 */
public class ContactNewFragment extends Fragment implements OnScrollListener {
    private ListView groupListView;
    
    private ContactAdpter smsAdpter;
    
    private ContactUserServiceImpl contactUserService;
    
    private Context context;
    
    private EditText editText;
    
    private CheckBox checkBox;
    
    private boolean checked = false;
    
    private boolean isGroup = true;
    
    private ImageView head_btn_back;
    
    private String groupId = null;
    
    private View progressView;
    
    private int visibleLastIndex = 0; // 最后的可视项索引
    
    private int visibleItemCount; // 当前窗口可见项总数
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        
        View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.load_more, null);
        progressView = loadMoreView.findViewById(R.id.pg);
        
        View view = inflater.inflate(R.layout.main_contact, null);
        editText = (EditText)view.findViewById(R.id.search_txt);
        checkBox = (CheckBox)view.findViewById(R.id.search_cb);
        groupListView = (ListView)view.findViewById(R.id.contact_group_list_item);
        head_btn_back = (ImageView)view.findViewById(R.id.head_btn_back);
        contactUserService = new ContactUserServiceImpl(this.getActivity());
        smsAdpter = new ContactAdpter(this.getActivity());
        context = this.getActivity();
        // 获取集p团通讯录
        List<UserUserContact> list = contactUserService.searchGroup(null);
        smsAdpter.assignment(list);
        
        groupListView.addFooterView(loadMoreView);
        groupListView.setOnScrollListener(this);
        
        groupListView.setAdapter(smsAdpter);
        groupListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
                final UserUserContact userContact = (UserUserContact)smsAdpter.getItem(arg2);
                if (Contact.CONTACT_TYPE_LOCAL.equals(userContact.getType())) {
                    createDialogContact(userContact);
                } else if (Contact.CONTACT_TYPE_ONLINE.equals(userContact.getType())) {
                    // 点击的是集团数据
                    createDialogContact(userContact);
                } else if (Contact.CONTACT_TYPE_GROUP.equals(userContact.getType())) {
                    // 点击分组
                    return true;
                }
                return true;
            }
            
            private void createDialogContact(final UserUserContact userContact) {
                Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("操作选择");
                builder.setItems(new String[] {"查看联系人", "编辑联系人"}, new DialogInterface.OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        
                        if (arg1 == 0) {
                            Intent intent = new Intent(getActivity(), LocalContactAddActivity.class);
                            intent.putExtra("phone", userContact.getPhone());
                            intent.putExtra("pagetype", 1);// 1是查看
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(getActivity(), LocalContactAddActivity.class);
                            intent.putExtra("phone", userContact.getPhone());
                            intent.putExtra("pagetype", 2);// 2是编辑
                            startActivity(intent);
                        }
                    }
                });
                builder.create();
                builder.show();
            }
            
        });
        
        groupListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserUserContact userContact = (UserUserContact)smsAdpter.getItem(position);
                if (Contact.CONTACT_TYPE_LOCAL.equals(userContact.getType())) {
                    String phone = userContact.getPhone();
                    // 点击的是本地通讯录
                    Intent mainIntent = new Intent(context, LocalContactAddActivity.class);
                    mainIntent.putExtra("phone", phone);
                    // 详情界面
                    mainIntent.putExtra("pagetype", 1);
                    startActivity(mainIntent);
                } else if (Contact.CONTACT_TYPE_ONLINE.equals(userContact.getType())) {
                    // 点击的是集团数据
                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                    Fragment fragment = null;
                    Bundle bundle = new Bundle();
                    fragment = new OnlineContactDetailFragment();
                    bundle.putString("userId", userContact.getId());
                    if (fragment != null) {
                        fragment.setArguments(bundle);
                        transaction.replace(R.id.container, fragment);
                        transaction.addToBackStack(null);
                        transaction.commitAllowingStateLoss();
                        // transaction.commit();
                    }
                } else if (Contact.CONTACT_TYPE_GROUP.equals(userContact.getType())) {
                    // 点击分组
                    head_btn_back.setVisibility(View.VISIBLE);
                    // checkBox.setVisibility(View.INVISIBLE);
                    smsAdpter.removeAll();
                    smsAdpter.notifyDataSetChanged();
                    smsAdpter.addCollection(contactUserService.searchContactUser(null, userContact.getId(),null));
                    smsAdpter.notifyDataSetChanged();
                    // 判断当前是否在分组数据位置
                    isGroup = false;
                    groupId = userContact.getId();
                }
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void afterTextChanged(Editable arg0) {
                String content = arg0.toString();
                if (checked) {
                    // 选中查询部门 查询部门数据
                    if ((content != null) && (!"".equals(content))) {
                        initGroupData(content);
                    } else {
                        // 判断之前是部门数据分组还是其他
                        if (isGroup) {
                            initGroupData(null);
                        } else {
                            initUserContactData(null, groupId);
                        }
                    }
                    
                } else {
                    // 查询联系人数据
                    if ((content != null) && (!"".equals(content))) {
                        initUserContactData(content, groupId);
                    } else {
                        // 判断之前是部门数据分组还是其他
                        if (isGroup) {
                            initGroupData(null);
                        } else {
                            initUserContactData(null, groupId);
                        }
                    }
                    
                }
            }
            
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
            
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
                
            }
            
        });
        //
        checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(CompoundButton button, boolean isChecked) {
                checked = isChecked;
                editText.setText("");
            }
            
        });
        head_btn_back.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View ediview) {
                head_btn_back.setVisibility(View.INVISIBLE);
                // 返回到分组数据
                isGroup = true;
                
                // 清空搜索框值
                editText.setText("");
                // 将分组ID置为空
                groupId = null;
                initGroupData(null);
            }
        });
        return view;
    }
    
    /**
     * 初始化分组数据
     */
    private void initGroupData(String content) {
        new BaseTask<String, String, List<UserUserContact>>(getActivity()) {
            
            @Override
            protected void onSuccess(List<UserUserContact> result) {
                smsAdpter.removeAll();
                smsAdpter.notifyDataSetChanged();
                smsAdpter.addCollection(result);
                smsAdpter.notifyDataSetChanged();
                checkBox.setVisibility(View.VISIBLE);
                
            }
            
            @Override
            protected List<UserUserContact> doInBack(String... params)
                throws Exception {
                return contactUserService.searchGroup(params[0]);
            }
        }.execute(content);
        
    }
    
    private void initUserContactData(String content, String groupId) {
        new BaseTask<String, String, List<UserUserContact>>(getActivity()) {
            
            @Override
            protected void onSuccess(List<UserUserContact> result) {
                smsAdpter.removeAll();
                smsAdpter.notifyDataSetChanged();
                smsAdpter.addCollection(result);
                smsAdpter.notifyDataSetChanged();
                head_btn_back.setVisibility(View.VISIBLE);
                
            }
            
            @Override
            protected List<UserUserContact> doInBack(String... params)
                throws Exception {
                return contactUserService.searchContactUser(params[0], params[1],null);
            }
        }.execute(content, groupId);
        
    }
    
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.visibleItemCount = visibleItemCount;
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
    }
    
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {/*
                                                                          * int itemsLastIndex = smsAdpter.getCount() -
                                                                          * 1; // 数据集最后一项的索引 int lastIndex =
                                                                          * itemsLastIndex + 1; // 加上底部的loadMoreView项 if
                                                                          * (scrollState ==
                                                                          * OnScrollListener.SCROLL_STATE_IDLE &&
                                                                          * visibleLastIndex == lastIndex) {
                                                                          * progressView.setVisibility(View.VISIBLE);
                                                                          * new Handler().postDelayed(new Runnable() {
                                                                          * 
                                                                          * @Override public void run() { loadMore(); }
                                                                          * 
                                                                          * }, 2000); }
                                                                          */
    }
    
    private void loadMore() {
        if (!isGroup) {
            smsAdpter.removeAll();
            List<UserUserContact> list = contactUserService.searchContactUser(null, Contact.CONTACT_TYPE_ONLINE,null);
            smsAdpter.addCollection(list);
            
            smsAdpter.notifyDataSetChanged(); // 数据集变化后,通知adapter
            groupListView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项
            progressView.setVisibility(View.GONE);
        }
        
    }
    
}
